package com.qymerge.manage.core.utils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * Desc
 * User cong.li
 * Date 2017/4/4
 * Time 22:42
 */
public class CommonUtil {

    /**
     * Object转换成String, 如果为null，则返回空字符串
     *
     * @param object
     * @return
     */
    public static String getStringNotNullValue(Object object) {
        if (object == null) {
            return "";
        } else {
            return object.toString();
        }
    }

    /**
     * Object转换成Integer,如果为null，则返回0
     *
     * @param object
     * @return
     */
    public static Integer getIntegerNotNull(Object object) {
        String objStr = String.valueOf(object);
        if ("null" == objStr) {
            return 0;
        } else {
            return Integer.valueOf(objStr);
        }
    }

    /**
     * Object转换成Long,如果为null，则返回0
     *
     * @param object
     * @return
     */
    public static Long getLongNotNull(Object object) {
        String objStr = String.valueOf(object);
        if ("null" == objStr) {
            return 0L;
        } else {
            return Long.valueOf(objStr);
        }
    }

    /**
     * Iterator转List
     *
     * @param iter
     * @param <T>
     * @return
     */
    public static <T> List<T> copyIterator(Iterator<T> iter) {
        List<T> copy = new ArrayList<T>();
        while (iter.hasNext()) {
            copy.add(iter.next());
        }
        return copy;
    }

    private static final String LOWERCASE = "abcdefghkmnpqrstuvwxyz"; // 避免易混淆字符
    private static final String UPPERCASE = "ABCDEFGHKMNPQRSTUVWXYZ";
    private static final String DIGITS = "23456789"; // 避免0,1
    private static final String SPECIAL = "!@#$%&*";

    public static String generatePassword(int length) {
        SecureRandom random = new SecureRandom();
        List<Character> chars = new ArrayList<>();

        // 确保每类字符至少一个
        chars.add(getRandomChar(LOWERCASE, random));
        chars.add(getRandomChar(UPPERCASE, random));
        chars.add(getRandomChar(DIGITS, random));
        chars.add(getRandomChar(SPECIAL, random));

        // 填充剩余长度
        String allChars = LOWERCASE + UPPERCASE + DIGITS + SPECIAL;
        for (int i = 4; i < length; i++) {
            chars.add(allChars.charAt(random.nextInt(allChars.length())));
        }

        // 打乱顺序
        Collections.shuffle(chars, random);
        StringBuilder sb = new StringBuilder();
        for (char c : chars) sb.append(c);
        return sb.toString();
    }

    private static char getRandomChar(String charSet, SecureRandom random) {
        return charSet.charAt(random.nextInt(charSet.length()));
    }

    public static void main(String[] args) {
        System.out.println(generatePassword(12)); // 例如：gT7#k9Px!L2*
    }

}
